package eip.chapter8.expiration.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mule.umo.UMOFilter;
import org.mule.umo.UMOMessage;

/**
 * Simple mule filter that checks whether a message is received within
 * a certain amount of time.
 * 
 * @author nl24167
 */
public class ExpirationCheckFilter implements UMOFilter {

	
	private final static Log LOG = LogFactory.getLog(ExpirationCheckFilter.class);
	
	/**
	 * Check whether a message is received in time
	 */
	public boolean accept(UMOMessage message) {
		long timestamp = message.getLongProperty(ExpirationRouter.EIP_TIMESTAMP,-1);
		int ttl = message.getIntProperty(ExpirationRouter.EIP_TTL,-1);
		
		// if the fields aren't here we've got nothing to check
		// so we just ignore the message
		if (timestamp == -1 || ttl == -1) {
			LOG.error("Received message without any timestamp/ttl information: " + message);
			return false;
		} else {
			long timeInTransit = System.currentTimeMillis() - timestamp;
			if (timeInTransit > ttl) {
				// message took too long
				return false;
			} else {
				// message arrived in time
				return true;
			}
		}
	}
}
